package fy.input.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import fy.config.FyConfig;
import fy.util.DBUtil;

public final class BudgetCostNumberDao {
	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(BudgetCostNumberDao.class);

	private String number;
	private String name;

	private static final String QUERY_COST_BY_NUMBER_NAME = "select fs.field0008 预算编号, fs.field0010 项目名称, to_char(fs.field0011,'fm9999999990.00') 金额, fs.field0012 部门, fs.field0013 车间 from formson_1440 fs left join formmain_1439 fa on fs.formmain_id = fa.id where fa.finishedflag = 1 and fs.field0008 like '%'||?||'%' and fs.field0010 like '%'||?||'%' order by fs.field0008 asc";
	private static final String ERROR = "{success : false , msg : '预算金额查询发生异常，请重试或者联系OA系统管理员。'}";

	public void setNumber(String number) {
		this.number = number;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String queryCost() {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		String result = null;
		try {
			conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());

			pst = conn.prepareStatement(QUERY_COST_BY_NUMBER_NAME);

			pst.setString(1, number);
			pst.setString(2, name);

			rs = pst.executeQuery();

			JSONObject jo = new JSONObject();
			while (rs.next()) {
				JSONObject row = new JSONObject();
				row.put("number", rs.getString(1));
				row.put("name", rs.getString(2));
				row.put("cost", rs.getString(3));
				row.put("dept", rs.getString(4));
				row.put("childDept", rs.getString(5));
				jo.append("data", row);
			}
			jo.put("success", true);
			result = jo.toString();
		} catch (Exception e) {
			DBUtil.rollback(conn);
			e.printStackTrace();
			log.error("预算金额查询失败", e);
			result = ERROR;
		} finally {
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(rs, pst, conn);
		}
		return result;
	}

}
